package cn.zf233.xcloud.util;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * Created by zf233 on 2021/5/16
 * 线程安全的日期工具类
 */
public class ThreadSafeDateUtil {

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm";

    private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT_THREAD_LOCAL = ThreadLocal.withInitial(() -> new SimpleDateFormat(DATE_FORMAT));

    public static String format(long milliSeconds) {
        SimpleDateFormat simpleDateFormat = ThreadSafeDateUtil.DATE_FORMAT_THREAD_LOCAL.get();
        return simpleDateFormat.format(milliSeconds);
    }

    public static long now() {
        return LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    public static String nowDate() {
        return format(now());
    }

    /*
        使用ThreadLocal实现
        使用格式转换完成后，建议手动调用remove()
        避免内存泄漏问题出现
    */
    public static void remove() {
        ThreadSafeDateUtil.DATE_FORMAT_THREAD_LOCAL.remove();
    }
}

